<?php

namespace Fox;

class Config {

	private $data = [];
	private $file;
	private $type;

	public function __construct($file, $type = 'PHP') {
		$this->file = $file;
		$this->type = $type;
		$this->init();
	}

	private function init() {
		if (is_file($this->file)) {
			if ($this->type == 'PHP') {
				$this->data = require $this->file;
			} else {
				$this->data = json_decode(file_get_contents($this->file), true);
			}
		}
	}

	public function set($name, $val) {

		$segs = explode('.', $name);
		$data = &$this->data;
		$count = count($segs);
		foreach ($segs as $index => $item) {
			if ($index == $count - 1) {
				$data[$item] = $val;
				break;
			}
			if (!(isset($data[$item]) && is_array($data[$item]))) {
				$data[$item] = [];
			}
			$data = &$data[$item];
		}

		return $this;
	}

	public function get($name = null) {

		if (is_null($name)) {
			return $this->data;
		}

		$segs = explode('.', $name);
		$config = $this->data;
		for ($i = 0; $i < count($segs); $i++) {
			$key = $segs[$i];
			if (isset($config[$key])) {
				$config = $config[$key];
			} else {
				return null;
			}
		}

		return $config;
	}

	public function save($file = false, $type = false) {

		if ($file !== false) {
			$this->file = $file;
		}
		if ($type !== false) {
			$this->type = $type;
		}

		$content = '';
		if ($this->type == 'PHP') {
			$content = '<?php ' . PHP_EOL . ' return ' . stripslashes(var_export($this->data, true)) . ";";
		} else {
			$content = json_encode($this->data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
		}

		file_put_contents($this->file, $content, LOCK_EX);
	}

}